import { login, logout, getInfo } from '@/api/iam/authorization'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { getMD5 } from '@/utils/index'

const state = {
  token: getToken('accessToken'),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USER_TYPE: (state, userType) => {
    state.userType = userType
  },
  SET_ACCESS_LEVEL: (state, accessLevel) => {
    state.accessLevel = accessLevel
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, grantType, authCode, clientId, csrfToken, userPhone, captchaValue, saltValue } = userInfo
    return new Promise((resolve, reject) => {
      const data = {
        grantType: grantType,
        authKey: grantType === 'PASSWORD' ? username : userPhone,
        authSecret: grantType === 'PASSWORD' ? getMD5(password, saltValue) : authCode,
        captchaValue: captchaValue,
        clientId: clientId,
        csrfToken: csrfToken
      }
      login(data).then(response => {
        localStorage.setItem('REFRESH_TOKEN', response.refreshToken)
        commit('SET_TOKEN', response.accessToken)
        setToken('accessToken', response.accessToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (!response) {
          reject('Verification failed, please Login again.')
        }

        const { headshotUrl, name, type, accessLevel, permissions } = response// name, avatar, permissions

        const data = {
          roles: [accessLevel],
          accessLevel: accessLevel,
          type: type,
          permissions: permissions,
          avatar: headshotUrl || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
          name: name
        }

        // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }
        commit('SET_ROLES', data.roles)
        commit('SET_NAME', data.name)
        commit('SET_AVATAR', data.avatar)
        commit('SET_INTRODUCTION', data.permissions)
        commit('SET_USER_TYPE', data.type)
        commit('SET_ACCESS_LEVEL', data.accessLevel)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_USER_TYPE', '')
        commit('SET_ACCESS_LEVEL', '')
        removeToken('accessToken')
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken('accessToken')
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken('accessToken', token)

    const { roles } = await dispatch('getInfo')
    console.log('user')
    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
